<template>
	<!-- #ifdef H5 -->
	<LoginModal v-model:visible="showLoginModal" :required="true" @login-success="onLoginSuccess" />
	<!-- #endif -->
	<view class="home-container">
		<view class="auth-prompt" v-if="!isUserLoggedIn">
			<view class="auth-content">
				<text class="auth-title">欢迎使用消企助手</text>
				<button class="auth-btn" open-type="getPhoneNumber" @getphonenumber="onGetPhoneNumber"
					:loading="authLoading" :disabled="authLoading">
					{{ authLoading ? '认证中...' : '微信快速登录' }}
				</button>
			</view>
		</view>


		<!-- 顶部用户信息 -->
		<view class="user-info" v-if="isUserLoggedIn">
			<view class="user-detail">
				<text class="user-name">{{ userDisplayName }}</text>
				<text class="user-position">{{ userPosition }}</text>
			</view>
			<view class="user-actions">
				<view class="date-info">
					<text class="date">{{ currentDate }}</text>
					<text class="weekday">{{ currentWeekday }}</text>
				</view>
			</view>
		</view>

		<!-- 快捷入口 -->
		<view class="quick-entry-section" v-if="isUserLoggedIn">
			<text class="section-title">快捷入口</text>
			<view class="quick-grid">
				<view class="quick-item" @tap="switchTab('/pages/attendance/attendance')">
					<view class="quick-icon blue">🕐</view>
					<text class="quick-text">打卡</text>
				</view>
				<view class="quick-item" @tap="navigateTo('/pages/apply/leave')">
					<view class="quick-icon green">📅</view>
					<text class="quick-text">请假</text>
				</view>
				<view class="quick-item" @tap="navigateTo('/pages/apply/purchase')">
					<view class="quick-icon red">🛒</view>
					<text class="quick-text">采购</text>
				</view>
				<view class="quick-item" @tap="navigateTo('/pages/apply/expense-payment')">
					<view class="quick-icon gray">💰</view>
					<text class="quick-text">费用</text>
				</view>
				<view class="quick-item" @tap="navigateTo('/pages/business-trip/business-trip')">
					<view class="quick-icon purple">✈️</view>
					<text class="quick-text">出差</text>
				</view>
				<view class="quick-item" @tap="navigateTo('/pages/expense/expense')">
					<view class="quick-icon yellow">🧾</view>
					<text class="quick-text">报销</text>
				</view>

				<view class="quick-item" @tap="navigateTo('/pages/seal/seal')">
					<view class="quick-icon indigo">🔖</view>
					<text class="quick-text">用章</text>
				</view>
				<view class="quick-item" @tap="navigateTo('/pages/vehicle/vehicle')">
					<view class="quick-icon pink">🚗</view>
					<text class="quick-text">用车</text>
				</view>
			</view>
		</view>

		<!-- 我的申请 -->
		<view class="my-applications" v-if="isUserLoggedIn">
			<text class="section-title">我的申请</text>
			<view class="application-list">
				<view v-if="applications.length === 0 && !applicationsLoading" class="empty-data">
					<text class="empty-text">暂无申请记录</text>
				</view>
				<template v-else>
					<view v-for="(item, index) in applications" :key="index" class="application-item"
						@tap="viewApplicationDetail(item)">
						<view class="application-content">
							<view class="application-header">
								<view class="application-header-left">
									<text class="icon">{{ getApplicationIcon(item.type) }}</text>
									<text class="application-title">{{ item.business_data.type_label }}</text>
								</view>
								<text :class="['application-status', getStatusClass(item.status)]">
									{{ getStatusText(item.status) }}
								</text>
							</view>
							<view class="application-detail">
								<text class="application-desc">{{ item.business_data.detail }}</text>
							</view>
						</view>

					</view>
				</template>
				<view v-if="applicationsLoading" class="loading-data">
					<text class="loading-text">加载中...</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
// #ifdef H5
import LoginModal from '@/components/LoginModal.vue'
// #endif

import { logout, shouldShowLoginModal } from '@/common/auth'
import { getCurrentUser, isLoggedIn, wxAuth, handleWxPhoneAuth } from '@/common/auth'
import type { UserInfo } from '@/common/auth'
import { userApi } from "@/common/api"
import { workflowApi } from "@/common/api"
import { STORAGE_KEYS } from '@/common/auth'
import { workflowUtils } from '@/common/api'
import { uiUtils } from '@/common/uiUtils'

const currentDate = ref<string>('')
const currentWeekday = ref<string>('')
const currentUser = ref<UserInfo | null>(null)

// 使用从uiUtils导入的函数
const { getApplicationIcon, getStatusText, getStatusClass } = uiUtils


const showLoginModal = ref(false)
const authLoading = ref(false)

// 我的申请列表数据
const applications = ref<any[]>([])
const applicationsLoading = ref<boolean>(false)

// 检查用户是否登录且有用户信息 - 用于模板判断
const isUserLoggedIn = computed(() => {
	return !!currentUser.value
})



// 计算属性
const userDisplayName = computed(() => {
	if (currentUser.value) {
		return currentUser.value.name || '用户'
	}
	return '未登录'
})

const userPosition = computed(() => {
	return '员工'
})

const updateDateTime = () => {
	const now = new Date()
	const year = now.getFullYear()
	const month = String(now.getMonth() + 1).padStart(2, '0')
	const day = String(now.getDate()).padStart(2, '0')
	currentDate.value = `${year}年${month}月${day}日`

	const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
	currentWeekday.value = weekdays[now.getDay()]
}

const loadUserInfo = () => {
	try {
		const user = getCurrentUser()
		if (user) {
			currentUser.value = user
		}
	} catch (error) {
		console.error('获取微信用户信息失败:', error)
	}
}


const checkLoginStatus = () => {
	try {
		const shouldShow = shouldShowLoginModal()

		if (shouldShow) {
			console.log('首页：需要显示登录框')
			setTimeout(() => {
				showLoginModal.value = true
			}, 500)
		} else {
			loadUserInfo()
		}
	} catch (error) {
		console.error('首页：检查登录状态失败:', error)
		setTimeout(() => {
			showLoginModal.value = true
		}, 500)
	}
}

// 登录成功回调
const onLoginSuccess = (userInfo: any) => {
	showLoginModal.value = false
	currentUser.value = userInfo
	const welcomeMessage = `欢迎回来，${userInfo.name}`

	uni.showToast({
		title: welcomeMessage,
		icon: 'success',
		duration: 2000
	})

	// 使用 nextTick 确保响应式数据更新后再加载申请列表
	uni.nextTick(() => {
		loadMyApplications()
	})
}


const handleLogout = () => {
	uni.showModal({
		title: '确认退出',
		content: '确定要退出登录吗？',
		success: (res: any) => {
			if (res.confirm) {
				logout()
			}
		}
	})
}

// 清除存储并刷新（调试用）
const clearStorageAndRefresh = () => {
	uni.showModal({
		title: '清除存储',
		content: '将清除所有本地存储数据并刷新页面，确定吗？',
		success: (res: any) => {
			if (res.confirm) {
				console.log('清除所有存储数据')
				uni.clearStorageSync()
				setTimeout(() => {
					window.location.reload()
				}, 500)
			}
		}
	})
}


const handleWxLogout = () => {
	uni.showModal({
		title: '确认退出',
		content: '确定要退出登录吗？',
		success: (res: any) => {
			if (res.confirm) {
				// 清除登录数据
				uni.clearStorageSync()

				// 清除当前用户信息
				currentUser.value = null

				uni.showToast({
					title: '已退出登录',
					icon: 'success',
					duration: 2000
				})

				console.log('用户已退出登录')
			}
		}
	})
}


// 获取手机号授权
const onGetPhoneNumber = async (e: any) => {
	console.log('获取手机号回调:', e)

	if (authLoading.value) return

	authLoading.value = true

	// 立即设置授权状态，避免闪烁
	uni.showLoading({
		title: '认证中...',
		mask: true
	})

	try {
		// 首先进行微信认证获取code
		const authResult: any = await wxAuth()

		if (authResult.needPhoneAuth) {
			// 处理手机号授权
			const userInfo = await handleWxPhoneAuth(e.detail)
			console.log("onGetPhoneNumber", userInfo)

			// 隐藏加载提示
			uni.hideLoading()

			// 调用登录成功回调，统一处理登录后的逻辑
			onLoginSuccess(userInfo)
		}

	} catch (error: any) {
		console.error('微信认证失败:', error)

		// 隐藏加载提示
		uni.hideLoading()

		let errorMessage = '认证失败，请联系管理员'
		let showModal = false

		if (error.message === 'PERMISSION_REQUIRED') {
			// 权限未开通的特殊处理
			uni.showModal({
				title: '权限配置提示',
				content: '小程序获取手机号权限未开通。\n\n请按以下步骤配置：\n1. 登录微信公众平台\n2. 进入开发管理 > 接口权限\n3. 找到"手机号快速验证组件"\n4. 点击开通并完成配置\n\n配置完成后重新发布小程序即可使用。',
				showCancel: true,
				confirmText: '我知道了',
				cancelText: '查看详情',
				success: (res: any) => {
					if (!res.confirm) {
						// 用户点击了"查看详情"，可以跳转到帮助页面或显示更多信息
						uni.showModal({
							title: '详细配置步骤',
							content: '1. 登录 mp.weixin.qq.com\n2. 开发管理 → 开发设置 → 接口权限\n3. 搜索"手机号快速验证"\n4. 点击"申请开通"\n5. 按要求填写申请信息\n6. 审核通过后重新发布小程序',
							showCancel: false,
							confirmText: '明白了'
						})
					}
				}
			})
			return // 直接返回，不再显示toast
		} else if (error.message.includes('用户拒绝授权')) {
			errorMessage = '需要授权获取手机号才能使用'
			showModal = true
		} else if (error.message.includes('获取手机号数据失败')) {
			errorMessage = '获取授权数据失败，请重试'
		} else if (error.message.includes('网络')) {
			errorMessage = '网络错误，请检查网络后重试'
		} else if (error.message.includes('请先进行微信认证')) {
			errorMessage = '微信认证异常，请重启小程序'
		}

		if (showModal) {
			uni.showModal({
				title: '授权提示',
				content: '为了正常使用系统功能，需要您授权获取手机号。请点击"微信快速登录"按钮并允许授权。',
				showCancel: false,
				confirmText: '我知道了'
			})
		} else {
			uni.showToast({
				title: errorMessage,
				icon: 'none',
				duration: 3000
			})
		}
	} finally {
		authLoading.value = false
	}
}


const navigateTo = (url: string) => {
	uni.navigateTo({
		url: url
	})
}

const switchTab = (url: string) => {
	uni.switchTab({
		url: url
	})
}

// 页面加载时初始化
onLoad(async () => {
	console.log("onLoad 执行")
	updateDateTime()
	// 加载用户信息
	await loadUserInfo()
})

// 页面每次显示时更新数据
onShow(() => {
	console.log("onShow 执行")
	// 加载我的申请列表
	isLoggedIn() && loadMyApplications()
})

// 加载我的申请列表
const loadMyApplications = async () => {
	if (!isUserLoggedIn.value) return

	applicationsLoading.value = true

	try {
		const res = await workflowApi.getMyApplications({ page: 1, limit: 10 })
		console.log("loadMyApplications", res)
		if (res.success) {
			// 对申请列表进行排序，将待处理的放在前面
			const items = res.data || []
			applications.value = items.sort((a: any, b: any) => {
				// 将 pending 状态的项目排在前面
				if (a.status === 'pending' && b.status !== 'pending') return -1
				if (a.status !== 'pending' && b.status === 'pending') return 1
				// 其他情况按时间倒序排列（假设有 created_at 字段）
				return 0
			})
			// console.log('我的申请列表加载成功:', applications.value)
		} else {
			console.error('获取我的申请列表失败:', res.message)
			uni.showToast({
				title: '获取申请列表失败',
				icon: 'none',
				duration: 2000
			})
		}
	} catch (error) {
		console.error('获取我的申请列表出错:', error)
	} finally {
		applicationsLoading.value = false
	}
}

// 查看申请详情
const viewApplicationDetail = (item: any) => {
	// 根据申请类型跳转到对应的详情页面
	const typeToPage: Record<string, string> = {
		'leave': '/pages/apply/leave',
		'business-trip': '/pages/business-trip/business-trip',
		'expense-payment': '/pages/apply/expense-payment',
		'purchase': '/pages/apply/purchase',
		'seal': '/pages/seal/seal',
		'vehicle': '/pages/vehicle/vehicle',
		'payment': '/pages/payment/payment'
	}

	const targetPage = typeToPage[item.type]
	if (targetPage) {
		// 使用 uni-app 的页面跳转
		uni.navigateTo({
			url: `${targetPage}?id=${item.business_id}`,
			success: () => {
				console.log('跳转到申请详情页成功')
			},
			fail: (err: UniApp.GeneralCallbackResult) => {
				console.error('跳转失败:', err)
				uni.showToast({
					title: '页面跳转失败',
					icon: 'none'
				})
			}
		})
	} else {
		uni.showToast({
			title: '暂不支持查看该类型申请',
			icon: 'none',
			duration: 2000
		})
	}
}
</script>

<style scoped>
.home-container {
	padding: 30rpx;
	background-color: #f5f6fa;
	min-height: 100vh;
	box-sizing: border-box;
}

.user-info {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
	will-change: transform;
}

.user-name {
	font-size: 36rpx;
	font-weight: 600;
	color: #333;
	display: block;
}

.user-position {
	font-size: 28rpx;
	color: #666;
	display: block;
	transform: translateY(8rpx);
}

.user-actions {
	text-align: right;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
}

.date,
.weekday {
	font-size: 28rpx;
	color: #666;
	display: block;
}

.section-title {
	font-size: 34rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 20rpx;
	display: block;
}

.quick-entry-section,
.my-applications {
	background: #fff;
	border-radius: 16rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
	will-change: transform;
}

.application-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
	background: transparent;
	transition: background-color 0.2s ease;
}

.application-item:last-child {
	border-bottom: none;
}

.application-item:active {
	background-color: #f9f9f9;
}

.application-content {
	display: flex;
	flex-direction: column;
	width: 100%;
}

.application-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 12rpx;
}

.application-header-left {
	display: flex;
	align-items: center;
}

.icon {
	font-size: 32rpx;
	margin-right: 16rpx;
}

.application-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	display: block;
}

.application-desc {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 8rpx;
	line-height: 1.6;
	white-space: pre-wrap;
}

.application-status {
	flex: 0 0 auto;
	padding-left: 6rpx;
	font-weight: 500;
	font-size: 28rpx;
}

.application-status.pending {
	color: #2196f3;
}

.application-status.approved {
	color: #4caf50;
}

.application-status.rejected {
	color: #f44336;
}

.quick-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 24rpx;
}

.quick-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20rpx 16rpx;
	border-radius: 12rpx;
	transition: transform 0.2s ease;
	will-change: transform;
}

.quick-item:active {
	transform: scale(0.95);
}

.quick-icon {
	width: 90rpx;
	height: 90rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
}

.quick-text {
	font-size: 28rpx;
	color: #333;
	display: block;
	transform: translateY(12rpx);
}

.quick-icon.blue {
	background: #e3f2fd;
}

.quick-icon.green {
	background: #e8f5e8;
}

.quick-icon.purple {
	background: #f3e5f5;
}

.quick-icon.yellow {
	background: #fff8e1;
}

.quick-icon.red {
	background: #ffebee;
}

.quick-icon.indigo {
	background: #e8eaf6;
}

.quick-icon.pink {
	background: #fce4ec;
}

.quick-icon.gray {
	background: #f5f5f5;
}

.empty-data,
.loading-data {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 0;
}

.empty-text,
.loading-text {
	font-size: 28rpx;
	color: #999;
}

.application-detail {
	display: flex;
	align-items: flex-start;
	flex-direction: column;
}

.auth-prompt {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: #f5f6fa;
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 60rpx;
}

.auth-content {
	text-align: center;
	background: #fff;
	border-radius: 24rpx;
	padding: 80rpx 60rpx;
	box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
	max-width: 600rpx;
	width: 100%;
	will-change: transform;
}

.auth-title {
	display: block;
	font-size: 48rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 24rpx;
}

.auth-btn {
	width: 100%;
	height: 96rpx;
	background: #07c160;
	color: white;
	border: none;
	border-radius: 48rpx;
	font-size: 32rpx;
	font-weight: 500;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 6rpx 16rpx rgba(7, 193, 96, 0.25);
	transition: transform 0.2s ease, box-shadow 0.2s ease;
	will-change: transform;
}

.auth-btn:not([disabled]):active {
	transform: translateY(4rpx);
	box-shadow: 0 2rpx 8rpx rgba(7, 193, 96, 0.2);
}

.auth-btn[disabled] {
	background: #ccc;
	box-shadow: none;
}

@media (max-width: 767px) {
	.quick-grid {
		gap: 20rpx;
	}

	.quick-icon {
		width: 80rpx;
		height: 80rpx;
	}

	.section-title {
		font-size: 32rpx;
	}
}
</style>